/**
 * Created by Administrator on 2017/10/17.
 */
angular.module('module.recommended')
    .controller('ReeditController', ReeditController);
ReeditController.$inject = ['$scope', '$stateParams', "FileUpload", "RecommendedService", "$localStorage", "$state"];
function ReeditController($scope, $stateParams, FileUpload, RecommendedService, $localStorage, $state) {

    var vm = this;
    if (!$localStorage[environmental + "shopid"]) {
        $localStorage.$reset();
        $state.go('login');
    }
    var shopid = $localStorage[environmental + "shopid"];
    vm.sureBtn = sureBtn; // 模态框
    vm.cancelBtn = cancelBtn; // 模态框

    function sureBtn() {
        vm.messageVisible = false;
    }

    function cancelBtn() {
        vm.messageVisible = false;
    }

    var shopid = $localStorage[environmental + "shopid"];
    vm.industrys = [
        {"num": 3},
        {"num": 5},
        {"num": 10}
    ];

    RecommendedService.getFoodInfo(shopid).$promise.then(function (data) {
        vm.foodinfo = data;
    });
    var filepic = FileUpload.getFile();
    if (filepic) {
        var reader = new FileReader();
        reader.readAsDataURL(filepic);
        reader.onload = function (e) {

            // 在页面上显示二进制数据
            $scope.$apply(function () {
                vm.pictureurl = e.target.result;
            })
        }
    } else {
        window.history.go(-1);
    }
    var t_img; // 定时器
    var isLoad = true; // 控制变量

    // 判断图片加载状况，加载完成后回调
    isImgLoad(function () {
        imageShear(filepic);
    });

    // 判断图片加载的函数
    function isImgLoad(callback) {
        $('.cover').each(function () {

            // 找到为0就将isLoad设为false，并退出each
            if (this.height === 0) {
                isLoad = false;
                return false;
            }
        });
        if (isLoad) {
            clearTimeout(t_img); // 清除定时器
            callback();

            // 为false，因为找到了没有加载完成的图，将调用定时器递归
        } else {
            isLoad = true;
            t_img = setTimeout(function () {
                isImgLoad(callback); // 递归扫描
            }, 500); // 我这里设置的是500毫秒就扫描一次，可以自己调整
        }
    }

    // vm.uploadLogo = uploadLogo;
    function uploadLogo(file) {
        if (!file) {
            return;
        }
        var maxWidth = 800,
            maxHeight = 480;
        changePicture(maxWidth, maxHeight, file, uploadPicture, true);
    }

    function changePicture(maxWidth, maxHeight, file, callback, fixedSize) {
        if (maxWidth && maxHeight) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var base64Img = e.target.result;

                // 图片压缩操作
                ImageResizer({
                    resizeMode: "auto",
                    fixedSize: fixedSize,
                    dataSource: base64Img,
                    dataSourceType: "base64",
                    maxWidth: maxWidth, // 允许的最大宽度
                    maxHeight: maxHeight, // 允许的最大高度。
                    onTmpImgGenerate: function (img) {
                        vm.picture = img.src;
                    },
                    success: function (resizeImgBase64, canvas) {
                        var blob = dataURLtoBlob(resizeImgBase64);
                        blob.name = file['name'];
                        file = blob;
                        callback(file);
                    }
                });
            };
            reader.readAsDataURL(file);
        } else {
            callback(file);
        }
    }

    function uploadPicture(file) {
        if (file) {
            vm.progressPercentage = 0;
            var typepicture = file.name.substring(file.name.indexOf("."));
            var afterstr = moveSpace(file.name);
            var filechange;
            if (afterstr == ".jpg" || afterstr == ".png" || afterstr == ".gif" || afterstr == ".jpeg" || afterstr == ".svg" || afterstr == ".bmp") {
                filechange = randomWord(true, 20, 33) + ".jpg";
            } else {
                filechange = afterstr.replace(typepicture, '.jpg');
            }
            FileUpload.uploadFileToUrl(file, filechange, progressTest).then(function (sucData) {
                var foodurl = sucData.data.faddress;
                var info = {
                    "shopid": shopid,
                    "positionid": vm.foodinfo.length + 1,
                    "foodurl": foodurl,
                    "foodname": foodurl.match(/[^\/\\/-]+$/)[0],
                    "crc32": sucData.data.crc32,
                    "foodtime": vm.industryname,
                };
                vm.foodinfo.push(info);
                RecommendedService.addFoodInfo(vm.foodinfo, function (data) {
                    vm.messageVisible = true;
                    vm.message = "上传成功！";
                    $state.go("recommended");
                    $("#recommendbtn").attr("disabled", false);
                }, function (error) {
                    vm.messageVisible = true;
                    vm.message = "上传失败！";
                    $("#recommendbtn").attr("disabled", false);
                    location.reload(true);
                });
            }, function (error) {
            });
        }
    }

    // 图片拖拽操作
    function imageShear(file) {
        var Cropper = window.Cropper;
        var URL = window.URL || window.webkitURL;
        var container = document.querySelector('.img-container');
        var image = container.getElementsByTagName('img').item(0);
        var download = document.getElementById('download');
        var actions = document.getElementById('actions');
        var options = {
            aspectRatio: 5 / 3,
            preview: '.img-preview',
            background: false,
            autoCrop: true,
            movable: false,
            strict: false,
            //zoomable: false,
            //ready: function (e) {
            //    //console.log(e.type);
            //},
            //cropstart: function (e) {
            //    //console.log(e.type, e.detail.action);
            //},
            //cropmove: function (e) {
            //    //console.log(e.type, e.detail.action);
            //},
            //cropend: function (e) {
            //    //console.log(e.type, e.detail.action);
            //},
            //crop: function (e) {
            //    var data = e.detail;
            //    //console.log(dataRotate);
            //    //dataRotate.value = typeof data.rotate !== 'undefined' ? data.rotate : '';
            //},
            //zoom: function (e) {
            //    //console.log(e.type, e.detail.ratio);
            //}
        };
        var cropper = new Cropper(image, options);
        var originalImageURL = image.src;
        var uploadedImageType = 'image/jpeg';
        var uploadedImageURL;

        // Tooltip
        $('[data-toggle="tooltip"]').tooltip();

        if (!document.createElement('canvas').getContext) {
            $('button[data-method="getCroppedCanvas"]').prop('disabled', true);
        }

        if (typeof document.createElement('cropper').style.transition === 'undefined') {
            $('button[data-method="rotate"]').prop('disabled', true);
            $('button[data-method="scale"]').prop('disabled', true);
        }
        //
        // Methods
        actions.querySelector('.docs-buttons').onclick = function (event) {
            var e = event || window.event;
            var target = e.target || e.srcElement;
            var cropped;
            var result;
            var input;
            var data;

            if (!cropper) {
                return;
            }

            while (target !== this) {
                if (target.getAttribute('data-method')) {
                    break;
                }

                target = target.parentNode;
            }

            if (target === this || target.disabled || target.className.indexOf('disabled') > -1) {
                return;
            }

            data = {
                method: target.getAttribute('data-method'),
                target: target.getAttribute('data-target'),
                option: target.getAttribute('data-option') || undefined,
                secondOption: target.getAttribute('data-second-option') || undefined
            };

            cropped = cropper.cropped;

            if (data.method) {
                if (typeof data.target !== 'undefined') {
                    input = document.querySelector(data.target);
                    if (!target.hasAttribute('data-option') && data.target && input) {
                        try {
                            data.option = JSON.parse(input.value);
                        } catch (e) {
                        }
                    }
                }
                switch (data.method) {
                    case 'rotate':
                        if (cropped && options.viewMode > 0) {
                            cropper.clear();
                        }

                        break;

                    case 'getCroppedCanvas':
                        try {
                            data.option = JSON.parse(data.option);
                        } catch (e) {
                            //console.log(e.message);
                        }

                        if (uploadedImageType === 'image/jpeg') {
                            if (!data.option) {
                                data.option = {};
                            }

                            data.option.fillColor = '#fff';
                        }

                        break;
                }
                result = cropper[data.method](data.option, data.secondOption);
                switch (data.method) {
                    case 'rotate':
                        if (cropped && options.viewMode > 0) {
                            cropper.crop();
                        }

                        break;

                    case 'scaleX':
                    case 'scaleY':
                        target.setAttribute('data-option', -data.option);
                        break;
                    case 'getCroppedCanvas':
                        if (result) {
                            $("#recommendbtn").attr("disabled", true);
                            var Blobpicture = dataURLtoBlob(result.toDataURL(uploadedImageType));
                            Blobpicture.name = file['name'];
                            uploadLogo(Blobpicture);
                        }

                        break;

                    case 'destroy':
                        cropper = null;

                        if (uploadedImageURL) {
                            URL.revokeObjectURL(uploadedImageURL);
                            uploadedImageURL = '';
                            image.src = originalImageURL;
                        }

                        break;
                }

                if (typeof result === 'object' && result !== cropper && input) {
                    try {
                        input.value = JSON.stringify(result);
                    } catch (e) {
                        //console.log(e.message);
                    }
                }
            }
        };

        document.body.onkeydown = function (event) {
            var e = event || window.event;

            if (!cropper || this.scrollTop > 300) {
                return;
            }

            console.log(e.keyCode);
            switch (e.keyCode) {
                case 37:
                    e.preventDefault();
                    cropper.move(-1, 0);
                    break;

                case 38:
                    e.preventDefault();
                    cropper.move(0, -1);
                    break;

                case 39:
                    e.preventDefault();
                    cropper.move(1, 0);
                    break;

                case 40:
                    e.preventDefault();
                    cropper.move(0, 1);
                    break;
            }
        };
        function dataURLtoBlob(dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type: mime});
        }
    }

    // 上传图片进度条
    function progressTest(evt) {
        vm.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        $(".progress-bar").css({width: vm.progressPercentage + "%"});
    }
}